# utils/audit.py
from models.audit import AuditLog
from extensions import db
from typing import Dict, Any
import uuid

def log_audit_event(
    user_id: str,
    event_type: str,
    object_type: str = "USER",
    object_id: str = "",
    data: Dict[str, Any] = None,
    old_data: Dict[str, Any] = None
):
    """
    记录系统审计日志
    
    参数:
        user_id: 操作执行用户ID
        event_type: 事件类型（如USER_CREATED、USER_UPDATED）
        object_type: 操作对象类型（如USER、MESSAGE）
        object_id: 操作对象ID
        data: 操作数据（新增/更新后的数据）
        old_data: 操作前的原始数据
    """
    try:
        # 确保参数有效性
        if not all([user_id, event_type, object_id]):
            raise ValueError("Missing required audit log parameters")
        
        # 创建审计日志记录
        audit_log = AuditLog(
            id=str(uuid.uuid4()),
            user_id=user_id,
            event_type=event_type,
            object_type=object_type,
            object_id=object_id,
            data=data,
            old_data=old_data
        )
        
        # 添加到数据库会话
        db.session.add(audit_log)
        db.session.commit()
        
        return True
    except Exception as e:
        # 确保审计日志记录失败不影响主流程
        db.session.rollback()
        print(f"[AUDIT ERROR] Failed to log audit event: {str(e)}")
        return False